<?php
namespace App\Services\WxMass;

use App\Models\WxMass;
use App\Services\EasyWechat;
use App\Services\WxErrorService;
use App\Services\WxMaterialService;
/**
 * 视频群发逻辑
 * @package App\Services\WxMass
 */
class WxMassVideo extends WxMassAbstract
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->msgName = '视频';
    }
    /**
     * 发送处理
     * @param $massId
     */
    public function handleSend($massId)
    {
        \DB::beginTransaction();
        try{
            $massData = WxMass::where('is_open', 1)->where('is_send', 0)->findOrFail($massId);
            if (empty($massData->push_time) || strtotime($massData->push_time) <= time()){
                //获取群发专用素材ID
                $mediaId = (new WxMaterialService())->createMaterial($massData->msg_type)->getMassMediaId($massData->material_id);
                $message = new \EasyWeChat\Kernel\Messages\Media($mediaId, 'mpvideo');
                try{
                    $apiRs = $this->sendMass($message, $massData->filter_rule);
                    $massData->errcode = $apiRs['errcode'] ?? 0;
                    $massData->errmsg = $apiRs['errmsg'] ?? '';
                    $massData->msg_id = $apiRs['msg_id'] ?? 0;
                    $massData->msg_data_id = $apiRs['msg_data_id'] ?? '';
                }catch (\Exception $e){
                    $massData->errcode = 1;
                    $massData->errmsg = $e->getMessage();
                }
                $massData->is_send = 1;
                $massData->save();
            }

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 群发预览
     * @param $massId
     * @param $to
     * @param string $previewType
     * @return bool
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public function preview($massId, $to, $previewType = 'touser')
    {
        $massData = WxMass::where('msg_id', 0)->findOrFail($massId);
        $app = EasyWechat::officialAccount();
        $mediaId = (new WxMaterialService())->createMaterial($massData->msg_type)->getMediaId($massData->material_id);
        if ($previewType == 'touser'){
            $apiRs = $app->broadcasting->previewVideo($mediaId, $to);
        }elseif ($previewType == 'wxname'){
            $apiRs = $app->broadcasting->previewVideo($mediaId, $to, $app->broadcasting::PREVIEW_BY_NAME);
        }
        WxErrorService::checkApiResponse($apiRs);
        return true;
    }
}